package com.java.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.java.dao.MasterDao;
import com.java.util.Md5Util;


/**
 * 使用注解标注过滤器
 * 
 * @WebFilter将一个实现了javax.servlet.Filter接口的类定义为过滤器 属性filterName声明过滤器的名称,可选
 *                                                属性urlPatterns指定要过滤
 *                                                的URL模式,也可使用属性value来声明.(
 *                                                指定要过滤的URL模式是必选属性)
 * 
 */
public class UserFilter implements Filter {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	private static final int userId = 0;

	public UserFilter(MasterDao masterDao){
		this.masterDao=masterDao;
	}

	protected FilterConfig filterConfig;

	public MasterDao masterDao;
	
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		logger.info("filter启动成功-------");
		this.filterConfig = arg0;
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		
		
		Map<Object, Object> map = new HashMap<Object, Object>();
		
		HttpServletRequest sr = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		Map<String, String[]> maap = sr.getParameterMap();
		resp.setHeader("Access-Control-Allow-Origin", "*");
		resp.setHeader("Access-Control-Allow-Methods", "GET, POST");
		
		System.out.println(JSON.parseObject(sr.getParameter("Jdata")).toJSONString());
		com.alibaba.fastjson.JSONObject json1 = JSON.parseObject(sr.getParameter("Jdata"));
    	com.alibaba.fastjson.JSONObject jsonData = JSON.parseObject(json1.get("head").toString());
    	logger.error("sr.getRequestURL().toString()"+sr.getRequestURL().toString());
		for (Entry<String, String[]> entry : maap.entrySet()) {  
			logger.error("Key = " + entry.getKey() + ", Value = " + maap.get(entry.getKey()).toString()+ ", type = " + entry.getValue());  
		} 
		
		//验证合法
		String userName = jsonData.getString("userName");
		Integer userId = jsonData.getInteger("userId");
		String token = jsonData.getString("token");
		Integer userType = jsonData.getInteger("userType");
		String tokenA = Md5Util.GetMD5Code(userType+"zglc"+userName+"cgbs");
		// 判断用户是否登录，如果没有，
		logger.error("token"+token);
		logger.error("tokenA"+tokenA);
		
		if (StringUtils.isEmpty(token) || !token.startsWith(tokenA)) {
			
			// 获锝当前的URL
			String strURL = sr.getRequestURL().toString();
			logger.error("user haven't login!1111    url:  " + strURL);
			if (strURL.indexOf("/user/loginJson") == -1) {
				try {
					map.put("loginFlag", false);
					map.put("loginType", 1);
					map.put("loginMsg", "user haven't login!");
					logger.error("user haven't login!    url:  " + strURL);
					resp.getWriter().println(JSON.toJSONString(map));
					resp.flushBuffer();

					return;
				} catch (IOException iox) {
					filterConfig.getServletContext().log(iox.getMessage());
				}
			}
		}
		chain.doFilter(request, response);

	}

	public void destroy() {
		// TODO Auto-generated method stub
		this.filterConfig = null;
	}

}